package cn.huaqingcheng.tool.core;

import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;

/**
 * 延迟初始化 / 缓存实现
 */
@EqualsAndHashCode
@RequiredArgsConstructor
public class DelayedInit<T> implements Supplier<T> {

    /**
     * 初始化方法
     */
    private final Supplier<T> init;

    /**
     * 初始化锁
     */
    private final Lock initLock = new ReentrantLock();

    /**
     * 缓存的实例
     */
    private T t;

    @Override
    public T get() {
        if (t == null) {
            initLock.lock();
            try {
                if (t != null) {
                    return t;
                }
                t = init.get();
            } finally {
                initLock.unlock();
            }
        }
        return t;
    }

}
